package com.cooper.controllers;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.rest.Get;

import com.cooper.constants.AppConstants;

public class ValidateCodeController {
	
	private static final List<Character> rdCharList = new ArrayList<Character>();
	
	static{
		for(char index='0'; index <= '9'; index++){
			rdCharList.add(index);
		}
		for(char index='A'; index <= 'Z'; index++){
			rdCharList.add(index);
		}
	}

	@Get
	public void execute(Invocation inv) throws Exception{
		inv.getResponse().setContentType("image/jpeg;charset=utf-8");
		int width = 60, height = 20;
		BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
		
		Graphics g = image.getGraphics();
		Random random = new Random();
		
		// 以下填充背景颜色
		g.setColor(this.getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		
//		 取随机产生的认证码(6位数字)
		StringBuffer rdBuffer = new StringBuffer();
		for (int i = 0; i < 4; i++) {
			char rd = rdCharList.get(random.nextInt(36));
			rdBuffer.append(rd);
		   // 将认证码显示到图象中
		   g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));         
		    // 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
		    g.drawString(rd+"", 13 * i + 6, 16);
		}
		
		//将验证码存入session
		inv.getRequest().getSession().setAttribute(AppConstants.VALIDATE_CODE_NAME, rdBuffer.toString());
		
		g.dispose();
		OutputStream output = inv.getResponse().getOutputStream();
		ImageIO.write(image, "jpeg", output);
		output.close();
	}
	
	/**
	 * 给定范围获得随机颜色
	 * @param fc
	 * @param bc
	 * @return
	 * @author tianlg
	 */
	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255){
			fc = 255;
		}
		if (bc > 255){
			bc = 255;
		}
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
}
